1
|
|
|
import {CommandHandler} from '@nestjs/cqrs'; |
2
|
|
|
import {Inject} from '@nestjs/common'; |
3
|
|
|
import {CreateQuoteCommand} from './CreateQuoteCommand'; |
4
|
|
|
import {IQuoteRepository} from 'src/Domain/Billing/Repository/IQuoteRepository'; |
5
|
|
|
import {Quote} from 'src/Domain/Billing/Quote.entity'; |
6
|
|
|
import {IProjectRepository} from 'src/Domain/Project/Repository/IProjectRepository'; |
7
|
|
|
import {ICustomerRepository} from 'src/Domain/Customer/Repository/ICustomerRepository'; |
8
|
|
|
import {Customer} from 'src/Domain/Customer/Customer.entity'; |
9
|
|
|
import {CustomerNotFoundException} from 'src/Domain/Customer/Exception/CustomerNotFoundException'; |
10
|
|
|
import {ProjectNotFoundException} from 'src/Domain/Project/Exception/ProjectNotFoundException'; |
11
|
|
|
import {QuoteIdGenerator} from 'src/Domain/Billing/QuoteIdGenerator'; |
12
|
|
|
import {ProjectNotAllowedException} from 'src/Domain/Billing/Exception/ProjectNotAllowedException'; |
13
|
|
|
|
14
|
|
|
@CommandHandler(CreateQuoteCommand) |
15
|
|
|
export class CreateQuoteCommandHandler { |
16
|
|
|
constructor( |
17
|
|
|
@Inject('IQuoteRepository') |
18
|
|
|
private readonly quoteRepository: IQuoteRepository, |
19
|
|
|
@Inject('ICustomerRepository') |
20
|
|
|
private readonly customerRepository: ICustomerRepository, |
21
|
|
|
@Inject('IProjectRepository') |
22
|
|
|
private readonly projectRepository: IProjectRepository, |
23
|
|
|
private readonly quoteIdGenerator: QuoteIdGenerator |
24
|
|
|
) {} |
25
|
|
|
|
26
|
|
|
public async execute(command: CreateQuoteCommand): Promise<string> { |
27
|
|
|
const {customerId, status, user, projectId} = command; |
28
|
|
|
let project = null; |
29
|
|
|
|
30
|
|
|
const customer = await this.customerRepository.findOneById(customerId); |
31
|
|
|
if (!(customer instanceof Customer)) { |
32
|
|
|
throw new CustomerNotFoundException(); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
if (projectId) { |
36
|
|
|
project = await this.projectRepository.findOneById(projectId); |
37
|
|
|
if (!project) { |
38
|
|
|
throw new ProjectNotFoundException(); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
if (project.getCustomer().getId() !== customer.getId()) { |
42
|
|
|
throw new ProjectNotAllowedException(); |
43
|
|
|
} |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
const quoteId = await this.quoteIdGenerator.generate(); |
47
|
|
|
const quote = await this.quoteRepository.save( |
48
|
|
|
new Quote(quoteId, status, user, customer, project) |
49
|
|
|
); |
50
|
|
|
|
51
|
|
|
return quote.getId(); |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
|